package com.zengjin.test.service.impl;

import ch.qos.logback.core.util.StringUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zengjin.test.common.PageResponse;
import com.zengjin.test.common.Query;
import com.zengjin.test.common.SuperUtil;
import com.zengjin.test.exception.CustomException;
import com.zengjin.test.mapper.UserMapper;
import com.zengjin.test.model.dto.UserDto;
import com.zengjin.test.model.en.User;
import com.zengjin.test.model.vo.UserVo;
import com.zengjin.test.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 19324
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public void create(UserDto userDto) {
        //1.获取参数
        String name = userDto.getName();
        Integer age = userDto.getAge();
        String sex = userDto.getSex();
        String address = userDto.getAddress();
        //2.判断是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        queryWrapper.eq("age", age);
        queryWrapper.eq("sex", sex);
        queryWrapper.eq("address", address);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            throw new CustomException("用户已存在");
        }
        //3.封装对象
        user = new User();
        user.setName(name);
        user.setAge(age);
        user.setSex(sex);
        user.setAddress(address);
        userMapper.insert(user);
    }

    @Override
    public UserVo queryByUserId(UserDto userDto) {
        //1.获取参数
        Long userId = userDto.getUserId();
        if(userId == null){
            throw new CustomException("查询参数不能为空");
        }
        //2.查询
        User user = userMapper.selectById(userId);
        if(user == null){
            throw new CustomException("用户不存在");
        }
        //3.封装对象
        return BeanUtil.copyProperties(user, UserVo.class);
    }

    @Override
    public UserVo queryByOther(UserDto userDto) {
        //1.获取参数
        List<Query> queryList = userDto.getQueryList();
        if(queryList == null){
            throw new CustomException("查询参数不能为空");
        }
        //2.查询
        Map<String, Object> queryMap = SuperUtil.listToMap(queryList);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(queryMap);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null){
            throw new CustomException("用户不存在");
        }
        //3.封装对象
        return BeanUtil.copyProperties(user, UserVo.class);
    }

    @Override
    public List<UserVo> queryAll() {
        //1.查询
        List<User> users = userMapper.selectList(null);
        // 2. 封装对象
        return users.stream().map(user -> BeanUtil.copyProperties(user, UserVo.class)).collect(Collectors.toList());
    }

    @Override
    public void deleteByUserId(UserDto userDto) {
        //1.获取参数
        Long userId = userDto.getUserId();
        if(userId == null){
            throw new CustomException("删除参数不能为空");
        }
        //2.删除
        userMapper.deleteById(userId);
        if(userMapper.selectById(userId) != null){
            throw new CustomException("删除失败");
        }
    }

    @Override
    public void updateByUserId(UserDto userDto) {
        //1.获取ID
        Long userId = userDto.getUserId();
        //2.获取参数
        String name = userDto.getName();
        Integer age = userDto.getAge();
        String sex = userDto.getSex();
        String address = userDto.getAddress();
        if(userId == null){
            throw new CustomException("修改参数不能为空");
        }
        //2.修改
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(User::getUserId, userId);
        lambdaUpdateWrapper.set(StringUtil.isNullOrEmpty(name),User::getName, name);
        lambdaUpdateWrapper.set(age!=null,User::getAge, age);
        lambdaUpdateWrapper.set(StringUtil.isNullOrEmpty(sex),User::getSex, sex);
        lambdaUpdateWrapper.set(StringUtil.isNullOrEmpty(address),User::getAddress, address);
        userMapper.update(null, lambdaUpdateWrapper);
    }

    @Override
    public PageResponse<UserVo> queryUserByPage(UserDto userDto) {
        //1.获取参数
        String sortBy = userDto.getSortBy();
        Boolean isAsc = userDto.getIsAsc();
        Page<User> page = userDto.toPageDefaultSortByUpdateTime();
        if(StrUtil.isNotBlank(sortBy)&& isAsc != null){
            page = userDto.toPage(sortBy, isAsc);
        }else if(StrUtil.isNotBlank(sortBy)){
            page = userDto.toPageWithSortBy(sortBy);
        }else if(isAsc != null){
            page = userDto.toPageWithIsAsc(isAsc);
        }

        List<Query> queryList = userDto.getQueryList();
        List<String> serachList = userDto.getSearchList();
        //2.查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(queryList != null && !queryList.isEmpty()){
            Map<String, Object> queryMap = SuperUtil.listToMap(queryList);
            queryWrapper.allEq(queryMap);
        }

        // 处理搜索字段
        if (serachList != null && !serachList.isEmpty()) {
            String searchName = userDto.getSearchName(); // 假设 userDto 中有 searchValue 字段
            queryWrapper.and(wrapper -> {
                for (String field : serachList) {
                    wrapper.or().like(field, searchName);
                }
            });
        }
        List<User> users = userMapper.selectList(queryWrapper);
        //3.封装
        List<UserVo> userVos = users.stream().map(user -> BeanUtil.copyProperties(user, UserVo.class)).collect(Collectors.toList());
        return PageResponse.of(page,userVos);
    }
}
